package top.wilbert.collegelink.user.controller;/**
 * @author augus
 * @create 2023-02-15-20:54
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;
import top.wilbert.collegelink.common.vo.UserResponseVo;
import top.wilbert.collegelink.user.entity.UserEntity;
import top.wilbert.collegelink.user.feign.ThirdPartFeignService;
import top.wilbert.collegelink.user.service.UserService;
import top.wilbert.collegelink.user.vo.LoginVerifyVo;
import top.wilbert.collegelink.user.vo.UserLoginVo;
import top.wilbert.collegelink.common.constant.AuthServerConstant;
import top.wilbert.collegelink.common.exception.BizCodeEnum;
import top.wilbert.collegelink.common.utils.R;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


/**
 * @author Augus
 * @ClassName:LoginController
 * @date 2023/2/15 20:54
 * @Version 1.0
 **/
@RestController
@RequestMapping("user/login")
public class LoginController {
    @Autowired
    private ThirdPartFeignService thirdPartFeignService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserService userService;

    /**
     * 根据手机号发送验证码（登录注册）
     * @param phone
     * @return
     */
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam String phone) {
        R result = userService.smsSendCode(phone, AuthServerConstant.SMS_CODE_CACHE_PREFIX);
        return result;
    }

    /**
     * 学生账号注册，手机号已获取
     * @param accountName
     * @param schoolId
     * @param schoolName
     * @param phone
     * @param isDefaultAvatar
     * @param avatar
     * @return
     */
    @PostMapping("/register")
    public R register(@RequestParam String accountName, @RequestParam Integer schoolId, @RequestParam String schoolName, @RequestParam String phone, @RequestParam Boolean isDefaultAvatar, @RequestPart("avatar") MultipartFile avatar) {
        UserEntity userEntity = new UserEntity();
        userEntity.setAccountName(accountName);
        userEntity.setSchoolId(schoolId);
        userEntity.setPhone(phone);
        userEntity.setSchoolName(schoolName);

        String avatarUrl = "";
        if(isDefaultAvatar == true){
            avatarUrl = "https://collegelink-avatar.oss-cn-hangzhou.aliyuncs.com/2023-02-27/2575f477-83aa-4fac-8087-85e67a8d4272.jpg";
        }else {
            //上传了头像，就将图片上传保存起来，并设置用户头像
            avatarUrl = thirdPartFeignService.uploadAvatar(avatar);
        }
        userEntity.setAvatarUrl(avatarUrl);

        userService.save(userEntity);
        UserResponseVo userResponseVo = new UserResponseVo();
        BeanUtils.copyProperties(userEntity, userResponseVo);
        //注册成功，生成令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        //存到redis
        String userInfo = JSON.toJSONString(userResponseVo);
        stringRedisTemplate.opsForValue().set(AuthServerConstant.LOGIN_USER_PREFIX + token, userInfo, 3, TimeUnit.DAYS);

        return R.ok().put("token", token).setData(userResponseVo);
    }


    @PostMapping("/company/register")
    public R companyRegister(@RequestParam String accountName, @RequestParam Integer companyId, @RequestParam String companyName, @RequestParam String phone, @RequestParam Boolean isDefaultAvatar, @RequestPart("avatar") MultipartFile avatar) {
        UserEntity userEntity = new UserEntity();
        userEntity.setAccountName(accountName);
        userEntity.setCompanyId(companyId);
        userEntity.setPhone(phone);
        userEntity.setCompanyName(companyName);

        String avatarUrl = "";
        if(isDefaultAvatar == true){
            avatarUrl = "https://collegelink-avatar.oss-cn-hangzhou.aliyuncs.com/2023-02-27/2575f477-83aa-4fac-8087-85e67a8d4272.jpg";
        }else {
            //上传了头像，就将图片上传保存起来，并设置用户头像
            avatarUrl = thirdPartFeignService.uploadAvatar(avatar);
        }
        userEntity.setAvatarUrl(avatarUrl);

        userService.save(userEntity);
        UserResponseVo userResponseVo = new UserResponseVo();
        BeanUtils.copyProperties(userEntity, userResponseVo);
        //注册成功，生成令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        //存到redis
        String userInfo = JSON.toJSONString(userResponseVo);
        stringRedisTemplate.opsForValue().set(AuthServerConstant.LOGIN_USER_PREFIX + token, userInfo, 3, TimeUnit.DAYS);

        return R.ok().put("token", token).setData(userResponseVo);
    }


    /**
     * 用请求头当中的token获取用户信息
     * @param request
     * @return
     */
    @GetMapping("/getUserOfLogin")
    public R getUserOfLogin(HttpServletRequest request){
        String token = request.getHeader("token");
        String s = stringRedisTemplate.opsForValue().get(AuthServerConstant.LOGIN_USER_PREFIX + token);
        UserResponseVo userResponseVo = JSONObject.parseObject(s, UserResponseVo.class);
        if (userResponseVo != null) {
            //获取到用户信息并返回，同时刷新token存储时间
            stringRedisTemplate.expire(AuthServerConstant.LOGIN_USER_PREFIX + token, 3, TimeUnit.DAYS);
            return R.ok().setData(userResponseVo);
        } else {
            //令牌已失效
            return R.error(BizCodeEnum.USER_TOKEN_EXCEPTION.getCode(), BizCodeEnum.USER_TOKEN_EXCEPTION.getMessage());
        }
    }

    /**
     * 退出登录
     * @param request
     * @return
     */
    @RequestMapping("/logout")
    public R logout(HttpServletRequest request) {
        String token = request.getHeader("token");
        stringRedisTemplate.delete(AuthServerConstant.LOGIN_USER_PREFIX + token);

        return R.ok();
    }

    /**
     * 用户登录：手机号密码登录
     * @param userLoginVo
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody UserLoginVo userLoginVo) {
        UserResponseVo userResponseVo = userService.login(userLoginVo);
        if (userResponseVo != null) {
            //登录成功，并生成Token令牌
            String token = UUID.randomUUID().toString().replace("-", "");
            //存到redis
            String userInfo = JSON.toJSONString(userResponseVo);
            stringRedisTemplate.opsForValue().set(AuthServerConstant.LOGIN_USER_PREFIX + token, userInfo, 3, TimeUnit.DAYS);
            return R.ok().put("token", token).setData(userResponseVo);
        } else {
            //登录失败
            System.out.println("用户登录失败");
            return R.error(BizCodeEnum.ACCOUNT_PASSWORD_EXCEPTION.getCode(), BizCodeEnum.ACCOUNT_PASSWORD_EXCEPTION.getMessage());
        }
    }

    /**
     * 手机号验证码登录，如果该手机号没有注册过，就进行注册
     * @param loginVerifyVo
     * @return
     */
    @PostMapping("/verify")
    public R verify(@RequestBody LoginVerifyVo loginVerifyVo) {
        String s = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + loginVerifyVo.getPhone());
        if (!StringUtils.isEmpty(s)) {
            if (loginVerifyVo.getCode().equals(s.split("_")[0])) {
                //查找手机号对应的用户信息
                UserResponseVo userResponseVo = userService.searchUserByPhone(loginVerifyVo.getPhone());
                if (userResponseVo != null) {
                    //登录成功，并生成Token令牌
                    String token = UUID.randomUUID().toString().replace("-", "");
                    //存到redis
                    String userInfo = JSON.toJSONString(userResponseVo);
                    stringRedisTemplate.opsForValue().set(AuthServerConstant.LOGIN_USER_PREFIX + token, userInfo, 3, TimeUnit.DAYS);
                    //验证码通过，删除验证码
                    stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + loginVerifyVo.getPhone());
                    return R.ok().put("token", token).setData(userResponseVo);
                } else {
                    //验证码通过，删除验证码
                    stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + loginVerifyVo.getPhone());
                    //该手机号未注册
                    return R.error(BizCodeEnum.USER_REGISTER_EXCEPTION.getCode(), BizCodeEnum.USER_REGISTER_EXCEPTION.getMessage());
                }
            } else {
                //验证码错误
                return R.error(BizCodeEnum.VERIFY_CODE_EXCEPTION.getCode(), BizCodeEnum.VERIFY_CODE_EXCEPTION.getMessage());
            }
        } else {
            //验证码未发送
            return R.error(BizCodeEnum.SEND_CODE_EXCEPTION.getCode(), BizCodeEnum.SEND_CODE_EXCEPTION.getMessage());
        }
    }


}
